package com.ykq.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.ykq.dao.PermissionDao;
import com.ykq.entity.Permission;
import com.ykq.service.PermissionService;
import com.ykq.util.CommonResult;
import com.ykq.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: tui-education
 * @description:
 * @author: 闫克起2
 * @create: 2022-04-13 10:47
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    @Override
    public List<Permission> findPermissionByUserid(String userid) {
        //根据用户id查询具有的权限
       List<Permission> permissions= permissionDao.selectByUserid(userid);
        return permissions;
    }

    //表示根据当前用户查询该用户具有的菜单
    @Override
    public CommonResult findMenuByUserid() {
        String token = WebUtil.getRequest().getHeader("token");
        JWTVerifier build = JWT.require(Algorithm.HMAC256("ykq-AAA")).build();
        String userid = build.verify(token).getClaim("userid").asString();
        List<Permission> permissions = permissionDao.selectMenuByUserid(userid);
        //为菜单分层--父子关系
        List<Permission> first=new ArrayList<>();

        //找到一级菜单
        for (Permission f:permissions) {
              if(f.getPid().equals("1")){
                 first.add(f);
              }
        }
        //方法的递归调用.
        for(Permission one:first){
            List<Permission> children = findChildren(permissions, one.getId());
            one.setChildren(children);
        }


        return new CommonResult(2000,"查询左侧菜单成功",first);
    }

    //查询对应菜单的子菜单 递归方法 一定要小心出现死循环
    public List<Permission> findChildren(List<Permission> list,String pid){
          List<Permission> children=new ArrayList<>();
          for(Permission permission:list){
                 if(permission.getPid().equals(pid)){
                      children.add(permission);
                 }
          }

          for(Permission c:children){
              List<Permission> children1 = findChildren(list, c.getId());
              c.setChildren(children1);
          }
          return children;
    }
}
